package server

import (
	"6-17yk/common/model/mysql"
	"6-17yk/common/pkg"
	"6-17yk/common/proto/user"
	"errors"
	"github.com/google/uuid"
	"gorm.io/gorm"
	"strconv"
	"time"
)

func OrderCreate(req *user.OrderCreateReq) (*user.OrderCreateResp, error) {
	show, err := mysql.DockerShow(int(req.DoctorId))
	if err != nil {
		return nil, errors.New("详情查询失败")
	}
	newString := uuid.NewString()
	order := mysql.Order{
		Model:         gorm.Model{},
		UserId:        int(req.UserId),
		InstitutionId: int(req.InstitutionId),
		TeamId:        int(req.TeamId),
		DoctorId:      int(req.DoctorId),
		OrderSn:       newString,
		ServicePack:   req.ServicePack,
		SingCycle:     req.SingCycle,
		EffectiveDate: time.Now(),
		Price:         float64(req.Price),
		Notes:         req.Notes,
		PayWay:        int(req.PayWay),
		OrderStatus:   int(req.OrderStatus),
	}
	err = mysql.OrderCreate(&order)
	if err != nil {
		return nil, errors.New("订单创建失败")
	}
	doctor := mysql.UserDoctor{
		Model:      gorm.Model{},
		Userid:     order.UserId,
		DoctorId:   order.DoctorId,
		DoctorName: show.DoctorName,
	}
	err = mysql.UserDoctorCreate(&doctor)
	if err != nil {
		return nil, errors.New("添加失败")
	}
	float := strconv.FormatFloat(order.Price, 'f', 2, 64)
	pay := pkg.ALiPay()
	aliPay := pay.AliPay("家庭医生预约", newString, float)
	return &user.OrderCreateResp{
		OrderSn: newString,
		Key:     aliPay,
	}, nil
}
